import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

// 定义时序图数据结构
interface TemporalGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  timestamp: string
}

// 修改任务状态枚举
enum TaskStatus {
  PENDING = "PENDING",
  RUNNING = "RUNNING", 
  COMPLETED = "COMPLETED",
  FAILED = "FAILED"
}

// 修改接口定义以避免重复定义
interface TSGEInputParams {
  graph_sequence: Array<{
    nodes: MPLPNode[];
    edges: MPLPEdge[];
  }>;
  embedding_dim: number;
  learning_rate: number;
  epochs: number;
  node_types?: Record<string, string>;
}

interface NodeEmbedding {
  node_id: string;
  embedding: number[];
  node_type?: string;
}

interface LinkPrediction {
  source: string;
  target: string;
  probability: number;
  time?: number;
}

interface TSGEOutputParams {
  node_embeddings: NodeEmbedding[];
  link_predictions?: LinkPrediction[];
  algorithm: string;
  parameters: Record<string, any>;
  train_loss_history?: number[];
}

// TSGE相关接口
interface TSGERequest {
  task_id: string;
  task_callback_url?: string;
  input_params: {
    tsge_params: TSGEInputParams;
  };
}

interface TSGEResponse {
  task_id: string;
  task_callback_url?: string;
  task_status: TaskStatus;
  task_progress: number;
  task_logs?: string;
  error_message?: string;
  output_params: {
    tsge_results: TSGEOutputParams;
  };
  metrics: any[]; // 这里可以根据Chart类型进一步定义
}

// DRPA相关接口
interface DRPAInputParams {
  data_flows: Array<Record<string, any>>;
  time_window: number;
  risk_threshold: number;
  sensitivity_weights: {
    data_type: number;
    access_frequency: number;
    user_privilege: number;
    historical_incidents: number;
  };
}

interface WindowAssessment {
  window_id: number;
  start_time: number;
  end_time: number;
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  flagged_flows: string[];
  mitigation_actions: string[];
}

interface DRPAOutputParams {
  assessments: WindowAssessment[];
  overall_risk_score: number;
  high_risk_patterns: Array<Record<string, any>>;
  recommended_actions: string[];
}

// DRPA请求和响应
interface DRPARequest {
  task_id: string;
  task_callback_url?: string;
  input_params: {
    drpa_params: DRPAInputParams;
  };
}

interface DRPAResponse {
  task_id: string;
  task_callback_url?: string;
  task_status: TaskStatus;
  task_progress: number;
  task_logs?: string;
  error_message?: string;
  output_params: {
    drpa_results: DRPAOutputParams;
  };
  metrics: any[]; // 这里可以根据Chart类型进一步定义
}

// 修改算法实现
export const dynamicRiskPreventionAlgorithm: Algorithm = {
  name: "动态风险预防算法(DRPA)",
  description: "基于时间窗口的动态数据流风险评估与预防算法",
  configOptions: [
    {
      id: "time_window",
      label: "时间窗口(秒)",
      type: "number",
      defaultValue: 60,
      placeholder: "60"
    },
    {
      id: "risk_threshold",
      label: "风险阈值",
      type: "number",
      defaultValue: 0.7,
      placeholder: "0.7"
    },
    {
      id: "sensitivity_weights",
      label: "敏感度权重配置",
      type: "textarea",
      defaultValue: JSON.stringify({
        data_type: 0.3,
        access_frequency: 0.2,
        user_privilege: 0.3,
        historical_incidents: 0.2
      }, null, 2),
      placeholder: `请输入JSON格式的敏感度权重配置，例如：
{
  "data_type": 0.3,
  "access_frequency": 0.2,
  "user_privilege": 0.3,
  "historical_incidents": 0.2
}
  敏感度权重用于计算风险评分，各项权重说明：
- data_type (数据类型权重): 评估数据敏感程度的权重，如机密文件权重较高
- access_frequency (访问频率权重): 评估数据访问频率异常程度的权重
- user_privilege (用户权限权重): 评估用户权限级别的权重
- historical_incidents (历史事件权重): 评估历史安全事件的影响权重

注意事项：
1. 所有权重值范围为0-1之间
2. 所有权重之和应等于1
3. 权重值越大表示该因素在风险评估中的重要性越高`
    },
    {
      id: "inputData",
      label: "数据流信息",
      type: "textarea",
      placeholder: `请输入JSON格式的数据流列表，例如：
[
  {
    "flow_id": "flow1",
    "timestamp": 1634567890,
    "data_type": "SENSITIVE",
    "user_id": "user1",
    "access_type": "READ",
    "resource_id": "resource1"
  }
]`
    }
  ],

  execute: async (config) => {
    try {
      const taskId = `drpa_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      let dataFlows;
      let sensitivityWeights;
      
      try {
        dataFlows = JSON.parse(config.inputData);
        sensitivityWeights = JSON.parse(config.sensitivity_weights);
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式");
      }

      const requestData: DRPARequest = {
        task_id: taskId,
        task_callback_url: "http://172.16.4.151:1122/api/drpa/callback",
        input_params: {
          drpa_params: {
            data_flows: dataFlows,
            time_window: Number(config.time_window) || 60,
            risk_threshold: Number(config.risk_threshold) || 0.7,
            sensitivity_weights: sensitivityWeights
          }
        }
      };

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/drpa/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      });

      if (!createResponse.ok) {
        const errorData = await createResponse.json();
        throw new Error(errorData.detail || "创建任务失败");
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/drpa/execute/${taskId}`, {
        method: "POST"
      });

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json();
        throw new Error(errorData.detail || "执行任务失败");
      }

      // 轮询获取结果
      let result;
      let attempts = 0;
      const maxAttempts = 60;

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/drpa/result/${taskId}`);
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json();
          throw new Error(errorData.detail || "获取结果失败");
        }

        result = await getResultResponse.json();
        
        if (result.task_status === "COMPLETED") {
          break;
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败");
        }

        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时");
      }

      const outputParams = result.output_params.drpa_results;
      
      // 生成结果摘要
      const resultText = `动态风险评估完成：
总体风险分数: ${outputParams.overall_risk_score.toFixed(2)}
评估窗口数量: ${outputParams.assessments.length}
高风险模式数量: ${outputParams.high_risk_patterns.length}

建议采取的行动:
${outputParams.recommended_actions.map((action: string) => `- ${action}`).join('\n')}

详细评估结果:
${outputParams.assessments.map((assessment: WindowAssessment) => `
时间窗口 ${assessment.window_id}:
- 开始时间: ${new Date(assessment.start_time * 1000).toLocaleString()}
- 结束时间: ${new Date(assessment.end_time * 1000).toLocaleString()}
- 风险分数: ${assessment.risk_score.toFixed(2)}
- 风险等级: ${assessment.risk_level}
- 标记的数据流: ${assessment.flagged_flows.length}个
`).join('\n')}`;

      return {
        result: resultText,
        steps: [],
        executionTime: 0,
        details: {
          assessments: outputParams.assessments,
          overall_risk_score: outputParams.overall_risk_score,
          high_risk_patterns: outputParams.high_risk_patterns,
          recommended_actions: outputParams.recommended_actions
        }
      };
    } catch (e: any) {
      console.error("DRPA算法执行出错:", e);
      throw e;
    }
  }
}; 